﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Entity;
using WCF;


namespace geekmeet
{
    /// <summary>
    /// The page that controls the profile page. Fields hold info about the logged in user, 
    /// and the user profile that is being viewed, if they are not the same.
    /// </summary>
    public partial class Profile : System.Web.UI.Page
    {
        GeekMeetService wcf = new GeekMeetService();
        ProfileComposite viewProfile;
        System.Guid loggedInuserGUID;
        System.Guid viewUserID;
        bool IsPremium = Roles.IsUserInRole("premiumuser");

        protected void Page_Load(object sender, EventArgs e)
        {
            loggedInuserGUID = (Guid)Membership.GetUser().ProviderUserKey;
            ToggleNerdometer();

            // Load profile data
            SetProfileMenu();
            GetProfileData();
            GetInterests();
            CalculateAge();

            // Load 'add friend' categories
            FriendsCategoryData.DataBind();

            // If premium and viewing a different user's profile, do a match
            if (IsPremium && (!viewUserID.Equals(loggedInuserGUID)))
                MatchEmUp();
            else
                lblNerdometerMessage.Text = "Du har inte premium :(";

            if (Request.QueryString["user"] == null)
            {
                viewProfile = wcf.GetProfile(loggedInuserGUID);
            }
            else
            {
                try
                {
                    viewUserID = System.Guid.Parse(Request.QueryString["user"]);
                    viewProfile = wcf.GetProfile(viewUserID);
                }
                catch
                {
                    Response.Redirect("Error404.aspx");
                }
            }
        }
        
        

        private void SetProfileMenu()
        {
            mnuProfileLinks.Items[0].NavigateUrl = "Wall.aspx?user=" + viewUserID.ToString();
            mnuProfileLinks.Items[1].NavigateUrl = "Friends.aspx?user=" + viewUserID.ToString();
        }

        private void GetProfileData()
        {
            // Profile being viewed
            viewProfile = wcf.GetProfile(viewUserID);
            hiddenID.Value = viewUserID.ToString();

            // Load image
            imgProfileImage.ImageUrl = "~/images/profilePictures/" + viewUserID + ".jpg";

            // Display gender icon
            if (viewProfile.Gender == "m")
                imgGender.ImageUrl = "~/images/icons/m.png";
            else if (viewProfile.Gender == "f")
                imgGender.ImageUrl = "~/images/icons/f.png";
            else
                imgGender.Visible = false;


            // Personal data
            lblUserName.Text = viewProfile.Username;
            lblName.Text = viewProfile.FirstName + " " + viewProfile.LastName;
            litProfileText.Text = viewProfile.Text;

            // Has user entered location data?
            // If yes, display it
            if (viewProfile.City != "")
                lblLocation.Text = "från " + viewProfile.City;

            if (viewProfile.Country != "Inget land valt")
                lblLocation.Text += ", " + viewProfile.Country;

            /* 
                 If the user is viewing another user's profile, check 
                 if they have a friendrequest between them and the status on the request.
                 If not - make it possible to send a request
            */
             if (!loggedInuserGUID.Equals(viewUserID))
            {
                bool isRequested = wcf.IsFriendRequested(loggedInuserGUID, viewUserID);
                bool isPending = wcf.IsFriendRequestPending(loggedInuserGUID, viewUserID);
                bool isAccepted = wcf.IsFriendAccepted(loggedInuserGUID, viewUserID);
                Guid requestFrom = wcf.GetFriendRequester(loggedInuserGUID, viewUserID);

                if (isRequested)
                {
                    if (!isPending && isAccepted)
                        multiviewFriendStatus.SetActiveView(viewAcceptedFriend);
                    else if (isPending && !isAccepted && (loggedInuserGUID == requestFrom))
                        multiviewFriendStatus.SetActiveView(viewRequestFromMe);
                    else if (isPending && !isAccepted && (viewUserID == requestFrom))
                        multiviewFriendStatus.SetActiveView(viewRequestToMe);
                    else if (!isAccepted && !isPending)
                        multiviewFriendStatus.SetActiveView(viewDeniedFriend);
                }
                else
                    multiviewFriendStatus.SetActiveView(viewAddFriend);
            }
        }

        /// <summary>
        /// Shows or hides nerdometer
        /// </summary>
        private void ToggleNerdometer()
        { 
            if (Request.QueryString["user"] == null)
            {
                viewUserID = loggedInuserGUID;
                multiviewNerdometer.SetActiveView(ViewNerdometerInvisible);
            }
            else
            {
                multiviewNerdometer.SetActiveView(viewNerdometer);
                try
                {

                    viewUserID = System.Guid.Parse(Request.QueryString["user"]);
                }
                catch
                {
                    Response.Redirect("Error404.aspx");
                }
           }
        }

        /// <summary>
        /// Calculate and show the age of the user
        /// </summary>
        private void CalculateAge()
        {
            DateTime now = DateTime.Now;
            DateTime userBirthDate = viewProfile.BirthDate;
            int days = (now - userBirthDate).Days;
            lblAge.Text = (days / 365).ToString() + " år";

        }

        /// <summary>
        /// Displays the interests
        /// </summary>
        private void GetInterests()
        {
            List<InterestComposite> interests = new List<InterestComposite>();
            interests = wcf.GetUserInterests(viewUserID);

            interestRepeater.DataSource = interests;
            interestRepeater.DataBind();
        }

        /// <summary>
        /// Sends a friend request
        /// </summary>
        protected void AddFriend()
        {
            wcf.BeFriends(loggedInuserGUID, viewUserID, int.Parse(ddlFriendCategory.SelectedValue));
            Response.Redirect("Profile.aspx?user=" + viewUserID);
        }

        protected void btnSendFriendRequest_Click(object sender, EventArgs e)
        {
            AddFriend();
        }

        /// <summary>
        /// Checks how well the users would work together
        /// </summary>
        private void MatchEmUp()
        {
            //Calculate the matchpoints
            Nerdometric match = new Nerdometric();
            match = match.calculateLove(loggedInuserGUID, viewUserID);

            //Based on matchpoints - show a bar ('the nerdometric') that illustrates the number of points
            Page.ClientScript.RegisterStartupScript(
                    this.GetType(), "showBar", "showBar(" + (match.MatchPoints * 10) + ");", true);
            lblNerdometerMessage.Text = match.MatchString;
        }
    }
}